<?php
/**
 * Created by PhpStorm.
 * User: Yieong
 * Date: 14/11/12
 * Time: 上午9:54
 */

class PubForm {

    private $items = array();
    private $operations = array();
    private $values = array();
    private $method;
    private $action;
    private $name;

    /**
     * 增加字段节点
     * @param $id               节点ID
     * @param $title            节点的文字说名
     * @param $type             节点类型（text | select | radio | checkbox）
     * @param array $args       可选其他属性（options | value | style）
     * @return $this
     */
    public function addItem($name, $type, $title='', $args=array()){

        $value = PubRequest::R($name);
        if(!isset($value)) $value = $args['value'];
        if(is_string($value)) $value = trim($value);

        $this->items[$name] = array(
            'name'  => $name,
            'title' => $title,
            'type'  => $type,
            'value' => $value,
            'args'  => $args
        );
        return $this;
    }

    public function addValue($key, $value){
        $this->values[$key] = $value;
        return $this;
    }

    public function addOperation($title, $type='input', $action='submit', $class='btn btn-primary', $name=''){
        $this->operations[$title] = array(
            'title'  => $title,
            'type'   => $type,
            'action' => $action,
            'class'  => $class,
        	'name'   => $name
        );
        return $this;
    }

    /**
     * @param $key      删除Key
     * @return $this
     */
    public function delItem($key){
        unset($this->items[$key]);
        return $this;
    }

    /**
     * @param $key      删除Key
     * @return $this
     */
    public function delOperation($key){
        unset($this->operations[$key]);
        return $this;
    }

    /**
     * 设置表单提交方法
     * @param $action
     * @param string $method
     */
    public function setAction($action, $method='POST'){
        $this->action = $action;
        $this->method = $method;
        return $this;
    }

    /**
     * 设置名称，则表单提交为一个数组
     * @param $name 数组的key值
     */
    public function setName($name){
        $this->name = $name;
        return $this;
    }

    /**
     * 输出表单的展示内容
     * @return array
     */
    public function show(){
        $items = $this->items;

        foreach($items as &$v){
            $attr = '';
            $args = $v['args'];
            if(isset($args['placeholder'])) $attr .= " placeholder=\"{$args['placeholder']}\" ";
            if(isset($args['style'])) $attr .= " style=\"{$args['style']}\" ";

            if(!empty($this->name)) $v['name'] = "{$this->name}[{$v['name']}]";
            $v['attr'] = $attr;
        }
        unset($v);

        return array(
            'method'     => $this->method,
            'action'     => $this->action,
            'items'      => $items,
            'operations' => $this->operations,
            'values'     => $this->values
        );
    }

} 